package com.logos.ruralrevitalization.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.logos.ruralrevitalization.entity.AuthUser;
import com.logos.ruralrevitalization.repository.ChatHistoryRepository;
import com.logos.ruralrevitalization.req.AuthUserReq;
import com.logos.ruralrevitalization.req.ChatReq;
import com.logos.ruralrevitalization.resp.ProductOrderResp;
import com.logos.ruralrevitalization.resp.RuralShowResp;
import com.logos.ruralrevitalization.result.Result;
import com.logos.ruralrevitalization.service.AuthUserService;
import com.logos.ruralrevitalization.utils.RuralLoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

/**
 * 用户表(AuthUser)表控制层
 *
 * @author rose
 * @since 2025-03-24 22:03:01
 */
@RestController
@RequestMapping("/user/rural")
@Slf4j
public class RuralController {
    @Resource
    private AuthUserService authUserService;

    @Resource
    private RuralLoginUtil ruralLoginUtil;

    @Resource
    private ChatHistoryRepository chatHistoryRepository;

    @Resource(name = "ruralChatClient")
    private ChatClient ruralChatClient;

    /**
     * 农户登录
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody AuthUserReq authUserReq) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RuralController.java.login.authUserRequest:{}", JSON.toJSONString(authUserReq));
            }
            Preconditions.checkArgument(StringUtils.isNotBlank(authUserReq.getPhone()), "手机号不能为空");
            Preconditions.checkNotNull(authUserReq.getPassword(), "密码不能为空");
            Preconditions.checkNotNull(authUserReq.getUserType(), "用户类型不能为空");
            String token = authUserService.login(authUserReq);
            log.info("RuralController.login.token:{}", token);
            return Result.ok(token);
        } catch (Exception e) {
            log.error("RuralController.login.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 农户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody AuthUserReq authUserReq) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RuralController.java.register.authUserRequest:{}", JSON.toJSONString(authUserReq));
            }
            Preconditions.checkArgument(StringUtils.isNotBlank(authUserReq.getUserName()), "用户名不能为空");
            Preconditions.checkArgument(StringUtils.isNotBlank(authUserReq.getPhone()), "手机号不能为空");
            Preconditions.checkNotNull(authUserReq.getPassword(), "密码不能为空");
            Preconditions.checkNotNull(authUserReq.getUserType(), "用户类型不能为空");
            String token = authUserService.register(authUserReq);
            log.info("RuralController.register.token:{}", token);
            return Result.ok(token);
        } catch (Exception e) {
            log.error("RuralController.register.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 农户查询个人信息
     */
    @GetMapping("/queryInfo")
    public Result<AuthUser> queryInfo() {
        try {
            String id = ruralLoginUtil.getId();
            if (StringUtils.isBlank(id)) {
                return Result.fail("请先登录");
            }
            log.info("RuralController.queryInfo.id:{}", id);
            AuthUser authUser = authUserService.queryById(Long.valueOf(id));
            return Result.ok(authUser);
        } catch (Exception e) {
            log.error("RuralController.queryInfo.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 修改农户个人信息
     */
    @PostMapping("/updateInfo")
    public Result<Boolean> updateInfo(@RequestBody AuthUserReq authUserReq) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RuralController.updateInfo.authUserRequest:{}", JSON.toJSONString(authUserReq));
            }
            String id = ruralLoginUtil.getId();
            if (StringUtils.isBlank(id)) {
                return Result.fail("请先登录");
            }
            authUserReq.setId(Long.valueOf(id));
            Boolean result = authUserService.updateInfo(authUserReq);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("RuralController.updateInfo.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 展示农户首页统计数据
     */
    @GetMapping("/show/totalCount")
    public Result<RuralShowResp> show() {
        try {
            String id = ruralLoginUtil.getId();
            if (StringUtils.isBlank(id)) {
                return Result.fail("请先登录");
            }
            long start = System.currentTimeMillis();
            RuralShowResp result = authUserService.show(Long.valueOf(id));
            log.info("RuralController.show.time:{}ms", System.currentTimeMillis() - start);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("RuralController.show.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 首页展示最近订单
     */
    @GetMapping("/show/order")
    public Result<List<ProductOrderResp>> queryOrder() {
        try {
            String id = ruralLoginUtil.getId();
            if (StringUtils.isBlank(id)) {
                return Result.fail("请先登录");
            }
            List<ProductOrderResp> result = authUserService.queryRuralOrder(Long.valueOf(id));
            return Result.ok(result);
        }catch (Exception e) {
            log.error("RuralController.queryOrder.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 农户的ai助手
     */
    @PostMapping("/ai")
    public Result<String> ai(@RequestBody ChatReq chatReq) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RuralController.ai.chatReq:{}", JSON.toJSONString(chatReq));
            }
            String userId = ruralLoginUtil.getId();
            if (StringUtils.isBlank(userId)){
                return Result.fail("请先登录");
            }
            Preconditions.checkNotNull(chatReq.getMessage(), "消息不能为空");
            Preconditions.checkNotNull(chatReq.getChatId(), "会话id不能为空");
            String chatId = chatReq.getChatId();
            chatHistoryRepository.save(userId,chatId);
            // 2.请求模型
            String result = ruralChatClient.prompt()
                    .user(chatReq.getMessage())
                    .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                    .call()
                    .content();
            return  Result.ok(result);
        }catch(Exception e){
            log.error("RuralController.ai.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

}

